package com.lm.statemachine.component;

import com.lm.statemachine.entry.Order;
import com.lm.statemachine.enums.OrderEvent;
import com.lm.statemachine.enums.OrderState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
import org.springframework.statemachine.annotation.OnTransition;
import org.springframework.statemachine.annotation.WithStateMachine;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
@WithStateMachine
public class OrderStateListenerComponent {
    private static final Logger log = LoggerFactory.getLogger(OrderStateListenerComponent.class);

    @OnTransition(source = "CREATED", target = "PAID")
    public void payTransition(Message<OrderEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("Handle Pay Order：{}", order);
        //TODO 其他业务 如保存订单状态
        Objects.requireNonNull(order).setState(OrderState.PAID);
    }

    @OnTransition(source = "PAID", target = "SHIPPED")
    public void shipTransition(Message<OrderEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("Handle Ship Order：{}", order);
        //TODO 其他业务 如更新订单
        Objects.requireNonNull(order).setState(OrderState.SHIPPED);
    }

    @OnTransition(source = "SHIPPED", target = "COMPLETED")
    public void completeTransition(Message<OrderEvent> message) {
        Order order = (Order) message.getHeaders().get("order");
        log.info("Handle Complete Order：{}", order);

        //TODO 其他业务 如更新订单
        Objects.requireNonNull(order).setState(OrderState.COMPLETED);
    }
}
